package cn.wit.summit.chwan.ui.activity;

import android.animation.Animator;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.RecyclerViewViewPageAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.request.DailyNewRequest;
import cn.wit.summit.chwan.models.response.DailyDiscoverResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.AnimatorUtils;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeBig;
import cn.wit.summit.chwan.widgets.recyclerviewViewpage.DividerItemDecoration;
import cn.wit.summit.chwan.widgets.recyclerviewViewpage.PagingScrollHelper;
import cn.wit.summit.chwan.widgets.rhythm.IRhythmItemListener;
import cn.wit.summit.chwan.widgets.rhythm.RhythmAdapter;
import cn.wit.summit.chwan.widgets.rhythm.RhythmLayout;
import retrofit2.Retrofit;

/**
 * 每日推荐
 * Created by Alan on 2018/4/17.
 */

public class DailyRecommendationActivity extends MyActivity implements PagingScrollHelper.onPageChangeListener {

    @Bind(R.id.topBarTitleTx)
    TextView topBarTitleTx;
    @Bind(R.id.box_rhythm)
    RhythmLayout boxRhythm;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.btn_rocket_to_head)
    ImageButton btnRocketToHead;
    @Bind(R.id.text_time_first)
    TextView textTimeFirst;
    @Bind(R.id.text_time_second)
    TextView textTimeSecond;
    @Bind(R.id.dailyRecommendRoolRl)
    RelativeLayout dailyRecommendRoolRl;
    @Bind(R.id.notNetFl)
    FrameLayout notNetFl;

    private int pn = 1;
    private int pc = 20;
    private int formPn = 1;

    private RhythmAdapter mRhythmAdapter;

    private RecyclerViewViewPageAdapter adapter;

    private PagingScrollHelper scrollHelper = new PagingScrollHelper();
    private RecyclerView.ItemDecoration lastItemDecoration = null;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily_recommendation);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        hideTitleBar();
        topBarTitleTx.setText(getResources().getString(R.string.recommend_daily_recommend_tx));

        initRecyclerViewViewPage();
        initRhythmView();

        getDailyNewData();
    }

    private void initRecyclerViewViewPage() {
        adapter = new RecyclerViewViewPageAdapter(this);
        recyclerview.setAdapter(adapter);
        scrollHelper.setUpRecycleView(recyclerview);
        scrollHelper.setOnPageChangeListener(this);
        switchLayout();
        recyclerview.setHorizontalScrollBarEnabled(true);
    }

    private RecyclerView.LayoutManager layoutManager;

    private void switchLayout() {
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL);

        if (layoutManager != null) {
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.removeItemDecoration(lastItemDecoration);
            recyclerview.addItemDecoration(itemDecoration);
            scrollHelper.updateLayoutManger();
            scrollHelper.scrollToPosition(0);
            lastItemDecoration = itemDecoration;
        }


    }

    private void initRhythmView() {
        //设置ScrollView滚动动画延迟执行的时间
        boxRhythm.setScrollRhythmStartDelayTime(100);
        //设置钢琴布局的高度 高度为钢琴布局item的宽度+10dp
        int height = (int) boxRhythm.getRhythmItemWidth() + 2 * (int) TypedValue.applyDimension(1, 8.0F, getResources().getDisplayMetrics());
        boxRhythm.getLayoutParams().height = height;

        boxRhythm.setRhythmListener(rhythmItemListener);
    }

    private void getDailyNewData() {
        notNetFl.setVisibility(View.GONE);
        recyclerview.setVisibility(View.VISIBLE);
        if (pn == 1)
            showLoading("");

        DailyNewRequest tempRequest = retrofitManager.getDailyDiscoverRequest(pn, pc);
        api.getDailyDiscover(tempRequest).enqueue(new MyCallback<ResponseBase<List<DailyDiscoverResponse>>>() {
            @Override
            public void onSuccess(ResponseBase<List<DailyDiscoverResponse>> model) {
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                cancelLoading();
                showToast(msg);
                if (code==-3) {
                    notNetFl.setVisibility(View.VISIBLE);
                    recyclerview.setVisibility(View.GONE);
                }
            }
        });
    }

    private void updataUi(List<DailyDiscoverResponse> data) {
        LogUtils.e(">>>>:" + data);
        if (data == null) {
            if (pn == 1)
                showToast(getResources().getString(R.string.list_nothng));
            return;
        }
        cancelLoading();
        adapter.addData(data);
        if (mRhythmAdapter == null) {
            mRhythmAdapter = new RhythmAdapter(mContext, boxRhythm, data);
            boxRhythm.setAdapter(mRhythmAdapter);
            boxRhythm.showRhythmAtPosition(0);
            changeUi(0);
//            cancelLoadingFinish();
        } else {
            mRhythmAdapter.addCardList(data);
        }
        if (data.size() > 0)
            pn++;
    }

    @OnClick({R.id.btn_rocket_to_head, R.id.bar_back_iv, R.id.notNetFl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_rocket_to_head:
                scrollHelper.scrollToPosition(0);
                break;
            case R.id.bar_back_iv:
                finish();
                break;
            case R.id.notNetFl:
                pn = 1;
                getDailyNewData();
                break;
        }
    }

    /**
     * 自定义钢琴控件的监听器
     */
    private IRhythmItemListener rhythmItemListener = new IRhythmItemListener() {
        public void onRhythmItemChanged(int paramInt) {
        }

        public void onSelected(final int paramInt) {
            LogUtils.e(">>>>>onSelected:" + paramInt);
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    scrollHelper.scrollToPosition(paramInt);
                }
            }, 100L);
        }

        public void onStartSwipe() {
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str));
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            if (view==null) {
                LogUtils.e("tbl>>>>(view==null)");
                adapter.notifyItemChanged(Integer.valueOf(str), "change");
                return;
            }
            DownloadViewStrokeBig itemView = view.findViewById(R.id.installButn);
            if (itemView == null) {
                return;
            }
            itemView.updateButn(table);
        }
    }

    @Override
    public void onPageChange(int index) {
        LogUtils.e(">>>>>onPageChange:" + index);
        //执行动画，改变升起的钢琴按钮
        if (mRhythmAdapter != null && mRhythmAdapter.getCount() > index) {
            boxRhythm.showRhythmAtPosition(index);
            if ((adapter.getItemCount() - index) <= 5 && formPn <= pn) {
                formPn += 1;
                getDailyNewData();
            }

            changeUi(index);
        }
    }

    private int mPreColor;

    private void changeUi(int index) {
        DailyDiscoverResponse dataTemp = mRhythmAdapter.getItem(index);

        //得到当前的背景颜色
        int currColor = getHexColor(dataTemp.getGame_discover_info().getBg_color());
        //执行颜色转换动画
        AnimatorUtils.showBackgroundColorAnimation(this.dailyRecommendRoolRl, mPreColor, currColor, 700);
        mPreColor = currColor;

        if (index > 1) {
            if (btnRocketToHead.getVisibility() == View.GONE) {
                btnRocketToHead.setVisibility(View.VISIBLE);
                AnimatorUtils.animViewFadeIn(this.btnRocketToHead);
            }
        } else if (this.btnRocketToHead.getVisibility() == View.VISIBLE) {
            AnimatorUtils.animViewFadeOut(this.btnRocketToHead).addListener(new Animator.AnimatorListener() {
                public void onAnimationCancel(Animator paramAnimator) {
                }

                public void onAnimationEnd(Animator paramAnimator) {
                    btnRocketToHead.setVisibility(View.GONE);
                }

                public void onAnimationRepeat(Animator paramAnimator) {
                }

                public void onAnimationStart(Animator paramAnimator) {
                }
            });
        }

        long t = Long.valueOf(dataTemp.getGame_discover_info().getAddtimes()) * 1000;
        Format f = new SimpleDateFormat("dd");
        String time = f.format(t);
        Format f1 = new SimpleDateFormat("MM EEEE");
        String time1 = f1.format(t);
        textTimeSecond.setText(time1.replace(" ", "月\n"));
        textTimeFirst.setText(time);

    }

    public int getHexColor(String paramString) {
        int i = Long.decode("0xff626262").intValue();
        try {
            int j = Color.parseColor(paramString.trim());
            return j;
        } catch (Exception localException) {
        }
        return i;
    }
}
